<template>
    <div class="p-2">
        <transition :enter-active-class="proxy?.animate.searchAnimate.enter"
            :leave-active-class="proxy?.animate.searchAnimate.leave">
            <searchrevealing>
                <el-tabs v-model="activeTab">
                    <el-form :model="queryParams" ref="queryFormRef" :inline="true" label-width="104px">
                        <el-form-item label="商品名称" prop="styleName">
                            <el-input v-model="queryParams.styleName" placeholder="请输入商品名称" clearable maxlength="50"
                                style="width: 220px" @keyup.enter="handleQuery" />
                        </el-form-item>
                        <el-form-item label="类目" prop="categoryIdList">
                            <el-cascader v-model="queryParams.categoryIdList" :options="options" style="width: 220px"
                                filterable clearable ref="categoryRef" placeholder="请选择"
                                :props="props" />
                        </el-form-item>
                        <el-form-item label="商品编码/69码" prop="content">
                            <el-input v-model="queryParams.content" placeholder="请输入" clearable maxlength="20"
                                style="width: 220px" @keyup.enter="handleQuery" />
                        </el-form-item>
                        <el-form-item label="供应商" prop="supplierId">
                            <el-select v-model="queryParams.supplierId" placeholder="请选择供应商" clearable filterable
                                v-selectLoad="selectLoad" :teleported="false" :fit-input-width="true" remote
                                :remote-method="searchQuery" class="supplierSelect" style="width: 220px"
                                :loading="supplierQueryLoading" @clear="handleClear">
                                <el-option v-for="dict in supplierNameOptions" :key="dict.value" :label="dict.label"
                                    :value="dict.value">
                                </el-option>
                                <template v-if="supplierLoading">
                                    <div class="supplierSelect_icon">
                                        <el-icon class="el-select-loading__icon">
                                            <Loading />
                                        </el-icon>
                                        <span class="el-select-loading__tips">{{ "正在加载" }}</span>
                                    </div>
                                </template>
                                <template #loading>
                                    <svg class="circular" viewBox="0 0 50 50">
                                        <circle class="path" cx="25" cy="25" r="20" fill="none" />
                                    </svg>
                                </template>
                            </el-select>
                        </el-form-item>
                        <el-form-item label="申请部门" prop="coreDeptId">
                            <el-select v-model="queryParams.coreDeptId" placeholder="请选择" clearable filterable
                                style="width: 220px">
                                <el-option v-for="dict in anchorList" :key="dict.deptId" :label="dict.deptName"
                                    :value="dict.deptId"></el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item label="部门类型" prop="types">
                            <el-select v-model="queryParams.types" placeholder="请选择部门类型" clearable filterable
                                @change="(e: string) => { departmentTypeChange('type', e) }" style="width: 220px">
                                <el-option v-for="dict in departmentTypeList" :key="dict.deptId" :label="dict.deptName"
                                    :value="dict.deptId" />
                            </el-select>
                        </el-form-item>
                        <el-form-item label="部门名称" prop="recruiterDeptId">
                            <el-select v-model="queryParams.recruiterDeptId" placeholder="请选择部门名称" clearable filterable
                                @change="deptChange" style="width: 220px">
                                <el-option v-for="dict in deptList" :key="dict.deptId" :label="dict.deptName"
                                    :value="dict.deptId" />
                            </el-select>
                        </el-form-item>
                        <el-form-item label="人员名称" prop="recruiterUserId">
                            <el-select v-model="queryParams.recruiterUserId" placeholder="请选择人员名称" clearable filterable
                                style="width: 220px">
                                <el-option v-for="dict in recruiterList" :key="dict.userId" :label="dict.nickName"
                                    :value="dict.userId" />
                            </el-select>
                        </el-form-item>
                        <el-form-item label="库存编码" prop="stockCode">
                            <el-input v-model="queryParams.stockCode" placeholder="请输入" clearable style="width: 220px"
                                @keyup.enter="handleQuery" />
                        </el-form-item>
                        <el-form-item label="申请时间" prop="putTime">
                            <el-date-picker value-format="YYYY-MM-DD" v-model="putTime" type="daterange"
                                @change="putPickerChange" start-placeholder="开始时间" end-placeholder="结束时间" clearable
                                style="width: 220px" />
                        </el-form-item>
                        <el-form-item label="对接群名" prop="groupName">
                            <el-input v-model="queryParams.groupName" placeholder="请输入" clearable style="width: 220px"
                                @keyup.enter="handleQuery" />
                        </el-form-item>
                        <el-form-item label="联系方式" prop="phone">
                            <el-input v-model="queryParams.phone" placeholder="请输入" clearable style="width: 220px"
                                @keyup.enter="handleQuery" />
                        </el-form-item>
                    </el-form>
                    <div class="form_button">
                        <el-button type="primary" @click="handleQuery" :loading="queryLoading">查询</el-button>
                        <el-button @click="resetQuery" :loading="queryLoading">重置</el-button>
                    </div>
                </el-tabs>
            </searchrevealing>
        </transition>
        <el-card shadow="never">
            <template #header>
                <el-col :span="1.5">
                </el-col>
                <right-toolbar v-model:showSearch="showSearch" @queryTable="getList" :name="'补样审批初审待审批'"
                    @updateColumn="getColmun"></right-toolbar>
            </template>
            <el-table v-loading="loading" :data="supplierAddProductsList" @selection-change="handleSelectionChange"
                border row-key="productsId" @header-dragend="dragEnd">
                <el-table-column v-for="(item, index) in pendingValuationColumns" :key="index" :label="item.label"
                    align="center" :prop="item.prop" show-overflow-tooltip :fixed="item.fixed" :width="item.width">
                    <template #default="scope">
                        <image-preview v-if="item.prop == 'productImage'" :src="scope.row.productImage" :width="50"
                            :height="50" />
                        <div v-if="item.prop == 'requestSampleNum'">{{ Number(scope.row.requestSampleNum) }}</div>
                    </template>
                </el-table-column>

                <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right">
                    <template #default="scope">
                        <el-button link type="primary" @click="handleGoodWarehousing(scope.row)" class="color_theme"
                            style="margin-left: 0px !important">审批</el-button>
                    </template>
                </el-table-column>
            </el-table>

            <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
                v-model:limit="queryParams.pageSize" @pagination="paginationChange" />
        </el-card>
        <!-- 核价 -->
        <commoditymodify @doClose="commoditymodifyClose" :commoditydetailsData="commoditymodifyData"
            :dialogInfoVisible="commoditymodifyVisible"></commoditymodify>
    </div>
</template>
<script setup name="pendingValuation" lang="ts">
const { proxy } = getCurrentInstance() as any;
import commoditymodify from './commoditymodify.vue'
import { getStockSampleList, getStockSampleById } from '@/api/group/productSelectionPricing'
import { QualityControlQuery, ContractTable } from '@/api/group/productSelectionPricing/types';
import { getUserList, getSystemList } from '@/api/group/qualityControl'
import { loginSupplierList } from '@/api/group/supplier/index'
import { getCategoryLists } from '@/api/group/productOutbound'
import { queryOperationDeptList } from '@/api/group/productSelectionPricing'
const anchorList = ref<{ deptName: string; deptId: string }[]>([]);
const pendingValuationColumns = ref()
const props = {
    multiple: true
}
const columnData = ref()
// 时间
const putTime = ref()

const activeTab = ref('qualityControl');
const showSearch = ref(true);
const loading = ref(true);
const total = ref(0);
const supplierAddProductsList = ref<ContractTable[]>([]);
const queryFormRef = ref<ElFormInstance>();
const ids = ref<Array<string | number>>([]);

// 部门类型
const departmentTypeList = ref<{ deptId: string; deptName: string; }[]>([])
// 部门名称
const deptList = ref<{ deptId: string; deptName: string; }[]>([])
// 人员名称
const recruiterList = ref<{ userId: string; nickName: string; }[]>([])
const categoryRef = ref();
const options = ref()
const supplierNameOptions = ref<any[]>([])
const supplierNameDate = ref({
    pageNum: 1,
    pageSize: 10,
    supplierName: ''
})
const supplierQueryLoading = ref(false)
const supplierLoading = ref(true)
const supplierNametotal = ref()
const queryLoading = ref(false)


const commoditymodifyVisible = ref(false)
const commoditymodifyData = ref<ContractTable>()


const data = reactive<PageData<{}, QualityControlQuery>>({
    form: {},
    queryParams: {
        pageNum: 1,
        pageSize: 10,
        content: undefined,
        categoryIdList: undefined,
        styleName: undefined,
        recruiterDeptId: undefined,
        recruiterUserId: undefined,
        supplierId: undefined,
        coreDeptId: undefined,
        types: undefined,
        stockCode: undefined,
        outStartTime: undefined,
        outEndTime: undefined,
        groupName: undefined,
        phone: undefined,
        status: 0
    },
    rules: {}
});
const { queryParams, form, rules } = toRefs(data);
// 获取供应商列表
const getHmSupplierList = async () => {
    supplierLoading.value = true
    const res = await loginSupplierList(supplierNameDate.value)
    const reshandle = res.rows.map((item: any) => (
        {
            label: item.supplierName,
            value: item.id
        }
    ))
    supplierNameOptions.value.push(...reshandle)
    supplierNametotal.value = res.total
    supplierLoading.value = false
}
// 获取选品部门
const getAnchor = async () => {
    const res = await queryOperationDeptList()
    anchorList.value = res.data
}

/** 获取类目 */
const getCategoryList = async () => {
    try {
        const res = await getCategoryLists();
        const processedData = renameField(res.data);
        options.value = processedData;
    } catch (error) {
        console.error('Failed to get category list:', error);
        options.value = [];
    }
}
const renameField = (arr: any[]) => {
    return arr.filter(item => item.categoryStatus === 0).map(element => {
        if (element.children) {
            element.children = renameField(element.children);
        }
        return {
            label: element.categoryName,
            value: element.categoryId,
            ...element,
        };
    });
}

/** select懒加载 */
const selectLoad = async () => {
    if (supplierNameOptions.value.length < supplierNametotal.value) {
        supplierNameDate.value.pageNum++;
        getHmSupplierList()
    }
}
/** 远程搜索 */
const searchQuery = async (query: string) => {
    supplierQueryLoading.value = true
    supplierNameOptions.value = []
    supplierNameDate.value.pageNum = 1;
    supplierNameDate.value.pageSize = 10
    supplierNameDate.value.supplierName = query
    await getHmSupplierList()
    supplierQueryLoading.value = false
}
/** 清空供应商 */
const handleClear = () => {
    supplierNameDate.value.supplierName = ''
    supplierNameOptions.value = []
    supplierNameDate.value.pageNum = 1;
    supplierNameDate.value.pageSize = 10
    getHmSupplierList()
}
/**
 * 部门筛选
 */
const departmentTypeChange = async (type: string, id: string) => {
    deptList.value = []
    recruiterList.value = []
    queryParams.value.recruiterDeptId = undefined
    queryParams.value.recruiterUserId = undefined
    if (id) {
        const res = await getSystemList({ parentId: id })
        if (type === 'init') {
            departmentTypeList.value = res.data
        } else {
            deptList.value = res.data
        }
    }
}

/**
 *  根据招商部获取招商员
 */
const deptChange = async (event: string) => {
    queryParams.value.recruiterUserId = undefined
    if (event) {
        const res = await getUserList({ deptId: event })
        recruiterList.value = res.rows
    } else {
        recruiterList.value = []
    }
}


/** 查询列表 */
const getList = async () => {
    try {
        loading.value = true;
        let params = {
            ...queryParams.value,
            recruiterDeptId: queryParams.value.recruiterDeptId ? queryParams.value.recruiterDeptId : queryParams.value.types
        }
        const res = await getStockSampleList(params);
        supplierAddProductsList.value = res.rows;
        total.value = res.total;
        loading.value = false;
        queryLoading.value = false
    } catch (e) {
    } finally {
        loading.value = false;
    }
};

/** 搜索按钮操作 */
const handleQuery = () => {
    queryLoading.value = true
    queryParams.value.pageNum = 1;
    getList();
};
// 完成时间筛选
const putPickerChange = (val: string[]) => {
    if (val) {
        queryParams.value.outStartTime = val[0]
        queryParams.value.outEndTime = val[1]
    } else {
        queryParams.value.outStartTime = undefined
        queryParams.value.outEndTime = undefined
    }
}
/** 重置按钮操作 */
const resetQuery = () => {
    queryFormRef.value?.resetFields();
    queryParams.value.categoryIdList = undefined
    recruiterList.value = []
    deptList.value = []
    putTime.value = undefined
    queryParams.value.outStartTime = undefined
    queryParams.value.outEndTime = undefined
    queryParams.value.status = 0
    handleClear();
    handleQuery();
};
/** 多选框选中数据 */
const handleSelectionChange = (selection: ContractTable[]) => {
    ids.value = selection.map((item) => item.id);
};

/** 去核价 */
const handleGoodWarehousing = async (row: ContractTable) => {
    const res: any = await getStockSampleById({
        id: row.id,
    });
    res.data.bigVideos = import.meta.env.VITE_APP_PIC_URL + res.data.bigVideo
    commoditymodifyData.value = res.data
    commoditymodifyVisible.value = true
};
// 去核价关闭
const commoditymodifyClose = () => {
    commoditymodifyVisible.value = false
    getList();
};

/** 获取colmun */
const getColmun = async () => {
    const columnDatas = await proxy?.useColumn('补样审批初审待审批')
    pendingValuationColumns.value = columnDatas.columnCustom
    columnData.value = columnDatas
    queryParams.value.pageSize = columnDatas.columnPageSize || 10
}
/** 拖拽事件 */
const dragEnd = async (newWidth: number, oldWidth: number, column: any, event: MouseEvent) => {
    columnData.value.columnCustom.map((item: any) => {
        if (item.prop == column.property) {
            item.width = newWidth
        }
    })
    await proxy?.useColumnUpdate(columnData.value, queryParams.value.pageSize)
}
/** 页数变化 */
const paginationChange = async () => {
    await getList();
    await proxy?.useColumnUpdate(columnData.value, queryParams.value.pageSize)
    getColmun()
}

onMounted(async () => {
    queryParams.value.pageNum = 1;
    departmentTypeChange('init', '1861962988832542721')
    await getColmun();
    await getList();
    getAnchor();
    getCategoryList();
});
</script>
<style lang="scss" scoped>
.two-line {
    overflow: hidden;
    display: -webkit-box;
    /* 将对象作为弹性伸缩盒子模型显示 */
    -webkit-line-clamp: 2;
    /* 行数，值可以改，表示展示X行后多余的缩略展示 */
    -webkit-box-orient: vertical;
    /* 设置或检索伸缩盒对象的子元素的排列方式 */
    word-break: break-all;
}

.mb96 {
    margin-bottom: 96px;
}

.form_button {
    display: flex;
    justify-content: flex-end;
}

.circular {
    display: inline;
    height: 30px;
    width: 30px;
    animation: loading-rotate 2s linear infinite;
}

.path {
    animation: loading-dash 1.5s ease-in-out infinite;
    stroke-dasharray: 90, 150;
    stroke-dashoffset: 0;
    stroke-width: 2;
    stroke: var(--el-color-primary);
    stroke-linecap: round;
}

.supplierSelect {
    :deep(.el-popper) {
        left: 0 !important;
        top: 34px !important;
        z-index: 7000 !important;
        width: 100% !important;
    }
}

:deep(.el-tabs__content) {
    overflow: visible !important;
}

.supplierSelect_icon {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 100%;
}

.el-select-loading {
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: initial;
    pointer-events: none;
    color: var(--el-color-info);
    font-size: 12px;

    &__icon {
        font-size: 16px;
        animation: rotate 1.5s linear infinite;
    }

    &__tips {
        margin-left: 6px;
    }

    @keyframes rotate {
        from {
            transform: rotate(0deg);
        }

        to {
            transform: rotate(360deg);
        }
    }
}

.el-select-loading__tips {
    color: #606266;
    font-size: 14px;
}

:deep(.el-card__header) {
    display: flex;
    justify-content: flex-end;
}
</style>